<template>
  <div
    class="order_new"
    element-loading-text="加载中..."
    v-loading="submitLoading"
    @click="visibleSearch ? (visibleSearch = false) : ''"
  >
    <!-- 创建工单 -->
    <div :style="{ width: `${headerWidth}px` }" class="top_app">
      <div class="create_order">
        <h4 class="title">新建工单</h4>
        <div class="btns" style="display: flex; align-items: center; gap: 5px">
          <h-plain-button @click="submitOrder(orderFormRef)">提交</h-plain-button>
          <h-button @click="onCancelOrder">取消</h-button>
        </div>
      </div>
    </div>

    <!-- 工单信息 -->
    <div class="serve_message">
      <div class="order_basic">
        <h4 class="title">工单信息</h4>
        <el-form
          ref="orderFormRef"
          :model="basicData"
          :rules="rules"
          class="oard_form"
          label-position="right"
          label-width="75"
        >
          <div style="display: flex; gap: 6vw">
            <div style="width: 24vw">
              <!-- 选择商家 -->
              <el-form-item v-if="basicData.source === 7" label="选择商家" prop="factoryId">
                <el-select
                  class="w200"
                  @change="changeFactory"
                  @clear="changeValue"
                  v-model="basicData.factoryId"
                  clearable
                  placeholder="请选择"
                  :loading="getFactorySelectPageLoading"
                >
                  <template #header>
                    <div style="display: flex; gap: 5px">
                      <el-input
                        v-model="valueSele"
                        @input="changeValue"
                        @keyup.enter="changeValue"
                      />
                      <h-plain-button @click="changeValue">搜索</h-plain-button>
                    </div>
                  </template>
                  <el-option
                    v-for="item in factoryOptional"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 工单来源 -->
              <el-form-item label="工单来源" prop="source">
                <el-select
                  v-model="basicData.source"
                  @change="changeSou"
                  class="w200"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in sources"
                    :key="index"
                    :label="item.title"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <!-- 工单类型 -->
              <el-form-item label="工单类型" prop="moduleId">
                <el-select
                  v-model="basicData.moduleId"
                  :loading="loading"
                  :filter-method="handleGetOrderTypeOptions"
                  clearable
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                >
                  <el-option
                    v-for="mod in modules"
                    :key="mod.name"
                    :disabled="mod.select"
                    :label="mod.name"
                    :value="mod.id"
                    @click="handleChangeModule(mod)"
                  />
                </el-select>
              </el-form-item>

              <!-- 质保状态 -->
              <el-form-item label="质保状态" prop="overinsured">
                <el-select
                  v-model="basicData.overinsured"
                  class="w200"
                  clearable
                  placeholder="请选择"
                >
                  <el-option :value="false" label="在保" />
                  <el-option :value="true" label="过保" />
                </el-select>
              </el-form-item>

              <!-- 旧件退回 -->
              <el-form-item label="旧件退回" prop="overinsured">
                <el-checkbox v-model="basicData.isReturn" />
              </el-form-item>

              <!-- 描述 -->
              <el-form-item label="描述" prop="content">
                <el-input
                  v-model="basicData.content"
                  :rows="2"
                  class="form-control"
                  maxlength="500"
                  placeholder="请输入描述"
                  show-word-limit
                  type="textarea"
                />
              </el-form-item>

              <!-- 上传附件 -->
              <el-form-item label="上传附件">
                <div class="upload_file">
                  <el-upload
                    v-model="fileList"
                    :auto-upload="false"
                    :on-change="handleChange"
                    :show-file-list="false"
                    accept="image/*,.pdf"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon class="up_icon">
                      <UploadFilled />
                    </el-icon>
                    <div>点击上传图片或者文件(最多10个附件)</div>
                  </el-upload>
                  <ul class="ul_list">
                    <li v-for="(item, index) in fileList" :key="index" class="li_item">
                      <div class="li_item_left">
                        <img
                          v-if="(item.name || '').replace(/.+\./, '') == 'pdf'"
                          :src="pdf"
                          alt=""
                          style="width: 30px; height: 30px"
                          @click.stop="lookFile(item.img)"
                        />
                        <el-image
                          v-else
                          :preview-src-list="[item.img]"
                          :src="item.img"
                          fit="contain"
                          style="width: 30px; height: 30px"
                        />
                        <span class="pic_name">{{ item.name }}</span>
                      </div>
                      <el-icon size="16" style="cursor: pointer" @click.stop="deleteItem(index)">
                        <Delete />
                      </el-icon>
                    </li>
                  </ul>
                </div>
              </el-form-item>
            </div>
            <div>
              <!-- 工单分类 -->
              <el-form-item label="工单分类">
                <el-cascader
                  v-model="type"
                  :before-filter="inputChangeType"
                  :options="types"
                  :props="CascaderProps"
                  class="w200"
                  clearable
                  filterable
                  placeholder="请选择"
                  @visible-change="changeType"
                />
              </el-form-item>

              <!-- 处理方式 -->
              <el-form-item label="处理方式">
                <el-cascader
                  v-model="method"
                  :before-filter="inputChangeMethod"
                  :options="methodss"
                  :props="CascaderProps"
                  class="w200"
                  clearable
                  filterable
                  placeholder="请选择"
                  @visible-change="changeMmethod"
                />
              </el-form-item>

              <!-- 报单时间 -->
              <el-form-item label="报单时间">
                <el-date-picker
                  v-model="now"
                  :default-value="new Date()"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm"
                  disabled
                />
              </el-form-item>

              <!-- 服务级别 -->
              <el-form-item label="服务级别">
                <el-select
                  v-model="grade"
                  :loading="loading"
                  :filter-method="getworkLevelPageSelect"
                  class="w200"
                  clearable
                  filterable
                  remote-show-suffix
                >
                  <el-option
                    v-for="item in grades"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 受理客服 -->
              <el-form-item label="受理客服">
                <el-select
                  v-model="customer"
                  :loading="loading"
                  :filter-method="getworkTeamPageSelect"
                  class="w200"
                  clearable
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                >
                  <el-option :value="0" label="按规则分配">
                    <div style="display: flex; justify-content: space-between; align-items: center">
                      <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                    </div>
                  </el-option>
                  <el-option
                    v-for="item in customers"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 分派服务商 -->
              <el-form-item label="分派服务商">
                <el-select
                  v-model="network"
                  :loading="loading"
                  :filter-method="getNetworkPageSelectList"
                  class="w200"
                  clearable
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                >
                  <el-option :value="0" label="按规则分配">
                    <div style="display: flex; justify-content: space-between; align-items: center">
                      <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                    </div>
                  </el-option>
                  <el-option
                    v-for="item in networks"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 自定义信息 -->
      <div v-if="submitFormShow" class="right_aside">
        <h4 class="title">自定义信息</h4>
        <div class="oard_form oard_form_">
          <el-form ref="formRef" :model="basicData" label-position="right" label-width="auto">
            <div v-for="(item, bigindex) in basicData.customfieldList" :key="bigindex">
              <el-form-item
                :label="item.name"
                :prop="`customfieldList[${bigindex}][${
                  item.type === 5 || item.type === 6 || item.type === 7 ? 'imgArr' : 'val'
                }]`"
                :required="item.required"
                :rules="[
                  { required: item.required, message: item.tip, trigger: ['blur', 'change'] },
                ]"
              >
                <!-- 文本 -->
                <el-input
                  v-if="item.type === 1"
                  style="width: 220px"
                  v-model="item.val"
                  :placeholder="item.tip"
                  clearable
                  type="text"
                />

                <!-- 多行文本 -->
                <el-input
                  v-if="item.type === 2"
                  style="width: 220px"
                  v-model="item.val"
                  :placeholder="item.tip"
                  :rows="1"
                  class="form-control"
                  maxlength="200"
                  show-word-limit
                  type="textarea"
                />

                <!-- 单选 -->
                <el-select
                  v-if="item.type === 3 && item.contents.length > 3"
                  v-model="item.val"
                  :placeholder="item.tip"
                  clearable
                >
                  <el-option v-for="i in item.contents" :key="i.id" :label="i.val" :value="i.val" />
                </el-select>
                <el-radio-group v-else-if="item.type === 3" v-model="item.val">
                  <el-radio v-for="(i, index) in item.contents" :key="index" :label="i.val"
                    >{{ i.val }}
                  </el-radio>
                </el-radio-group>

                <!-- 多选 -->
                <el-select
                  v-if="item.type === 4 && item.contents.length > 3"
                  v-model="item.val"
                  :placeholder="item.tip"
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  multiple
                >
                  <el-option v-for="i in item.contents" :key="i.id" :label="i.val" :value="i.val" />
                </el-select>
                <el-checkbox-group v-else-if="item.type === 4" v-model="item.val">
                  <el-checkbox v-for="i in item.contents" :key="i.id" :value="i.val"
                    >{{ i.val }}
                  </el-checkbox>
                </el-checkbox-group>
                <!-- 图片 -->
                <div
                  v-if="item.type === 5 || item.type === 6 || item.type === 7"
                  :key="bigindex"
                  class="upload_file"
                >
                  <el-upload
                    v-model="item.imgArr"
                    :accept="item.type == 5 ? 'image/*' : item.type == 6 ? '.pdf' : 'video/*'"
                    :auto-upload="false"
                    :on-change="(file) => handleChange2(file, item)"
                    :show-file-list="false"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon class="up_icon">
                      <UploadFilled />
                    </el-icon>
                    <div>点击上传图片或者文件</div>
                  </el-upload>
                  <ul class="ul_list">
                    <li v-for="(it, index) in item.imgArr" :key="index" class="li_item">
                      <div class="li_item_left">
                        <img
                          v-if="it.name.replace(/.+\./, '') == 'pdf'"
                          :src="pdf"
                          alt=""
                          style="width: 30px; height: 30px; cursor: pointer"
                          @click.stop="lookFile(it.image)"
                        />
                        <el-icon
                          v-else-if="it.file.type.includes('video/')"
                          size="30"
                          style="cursor: pointer"
                          @click.stop="lookFile(it.image)"
                        >
                          <Film />
                        </el-icon>
                        <el-image
                          v-else
                          :preview-src-list="[it.image]"
                          :src="it.image"
                          fit="contain"
                          style="width: 30px; height: 30px"
                        />
                        <span class="pic_name">{{ it.name }}</span>
                      </div>
                      <el-icon
                        size="16"
                        style="cursor: pointer"
                        @click.stop="deleteItem2(bigindex, index)"
                      >
                        <Delete />
                      </el-icon>
                    </li>
                  </ul>
                </div>
                <!-- 评分 -->
                <el-rate v-if="item.type === 8" v-model="item.val" allow-half />
                <span v-if="item.type === 8">{{ item.val * 2 }}</span>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 客户信息 -->
    <div ref="cutomerInfoRef" class="basic_order">
      <div style="display: flex; align-items: center; gap: 5px">
        <h4 class="title">客户信息</h4>
        <HPlainButton :padding-lr="6" :height="22" @click="onAddrParse" :loading="addrParseLoading"
          >识别</HPlainButton
        >
      </div>
      <el-form
        ref="ruleFormRef2"
        :model="basicData"
        :rules="rules"
        class="oard_form"
        label-position="right"
      >
        <div class="userinfo">
          <!--地址识别-->
          <div class="address_identify">
            <el-form-item label="地址识别">
              <div class="address_identify_content">
                <el-input
                  v-model="allUserInfo"
                  class="textarea"
                  maxlength="300"
                  show-word-limit
                  placeholder="粘贴整段信息到此文本框如：张三，15815151515，北京市市辖区石景山区中山路25号"
                  rows="3"
                  type="textarea"
                />
              </div>
            </el-form-item>
          </div>

          <!--客户姓名、客户手机号-->
          <div>
            <el-form-item label-width="85" label="客户名称" prop="name">
              <!-- 根据商家带出客户列表 -->
              <el-popover
                v-if="basicData.source === 7"
                ref="popoverInputRef"
                popper-class="monitor-yt-popover"
                :width="220"
                :visible="visibleSearch"
                placement="bottom"
              >
                <div style="max-height: 380px; overflow: auto">
                  <p
                    v-if="userPageOptional.length == 0"
                    style="color: #999; text-align: center; padding: 12px 0"
                    >暂无数据
                  </p>
                  <div
                    class="user_item"
                    @click.stop="changeuserPeerson(item)"
                    v-for="(item, index) in userPageOptional"
                    :value="item.id"
                    :label="item.phone"
                    :item="item"
                    :key="index"
                    >{{ item.name }}{{ item.phone }}</div
                  >
                </div>
                <template #reference>
                  <el-input
                    @click="getFacUserList('')"
                    placeholder="请输入客户名称"
                    v-model="basicData.name"
                    @input="inputSearchName"
                    @clear="onClearUser"
                  />
                </template>
              </el-popover>
              <el-popover
                v-else
                ref="popoverInputRef"
                popper-class="monitor-yt-popover"
                :width="220"
                :visible="visibleSearch"
                placement="bottom"
              >
                <div style="max-height: 380px; overflow: auto">
                  <p
                    v-if="userPersons.length == 0"
                    style="color: #999; text-align: center; padding: 12px 0"
                    >暂无数据</p
                  >
                  <div
                    class="user_item"
                    @click="changeuserPeerson(item)"
                    v-for="(item, index) in userPersons"
                    :value="item.id"
                    :label="item.phone"
                    :item="item"
                    :key="index"
                    >{{ item.name }}{{ item.phone }}</div
                  >
                </div>
                <template #reference>
                  <el-input
                    style="width: 280px"
                    @click="getselecUser('')"
                    placeholder="请输入客户名称"
                    v-model="basicData.name"
                    @input="inputSearchName"
                    @clear="onClearUser"
                  />
                </template>
              </el-popover>
            </el-form-item>
            <el-form-item style="width: 320px" class="customer_phone" label="客户地址" required>
              <SingleAddress ref="singleAddressRef" :address="addrs" />
            </el-form-item>
          </div>

          <!--客户地址、详细地址-->
          <div style="width: 100%">
            <div style="display: flex; gap: 20px">
              <el-form-item class="customer_address" label="客户手机号" prop="phone">
                <el-input
                  v-model="basicData.phone"
                  @input="basicData.phone = basicData.phone.replace(/[^0-9]/g, '')"
                  maxlength="11"
                  placeholder="请输入客户手机号"
                />
              </el-form-item>
              <el-form-item class="customer_address" label="分机号">
                <el-input placeholder="请输入分机号" v-model="basicData.extensionNbr" />
              </el-form-item>
            </div>
            <el-form-item class="detail_address" label="详细地址" prop="address">
              <el-input
                v-model="basicData.address"
                :autosize="{ minRows: 2, maxRows: 3 }"
                maxlength="200"
                placeholder="请输入详细地址"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 商品信息 -->
    <div class="good_info">
      <Commoditynformation
        :orderGoodsList="orderGoodsTypes"
        :userPerson="basicData.userId"
        @get-order-goods-vos="orderGoodsTypes = $event"
        :factory-id="basicData.factoryId"
        ref="commodityRef"
      />
    </div>
    <!-- 文件查看 -->
    <el-dialog
      v-model="dialogContract"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :draggable="true"
      title="查看附件"
    >
      <iframe
        :src="`${file}`"
        frameborder="0"
        height="100%"
        style="height: 700px"
        width="100%"
      ></iframe>
    </el-dialog>

    <!-- 创建客户 -->
    <el-dialog v-model="createUserDialogVisit" :draggable="true" title="创建客户" width="400px">
      <el-form
        ref="createUserRef"
        :model="createUserForm"
        :rules="createUserFormRules"
        label-position="left"
        label-width="90px"
      >
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="createUserForm.name" clearable placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="客户手机号" prop="phone">
          <el-input
            v-model="createUserForm.phone"
            @input="createUserForm.phone = createUserForm.phone.replace(/[^0-9]/g, '')"
            clearable
            maxlength="11"
            placeholder="请输入客户手机号"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createUserDialogVisit = false">取消</el-button>
          <el-button class="btn-bg2" @click="onSaveCreateUser(createUserRef)">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
  import { Delete, Film, UploadFilled } from '@element-plus/icons-vue'
  import pdf from '@/assets/image/pdf.png'
  import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import {
    addSave,
    getModuleField,
    getUserSelect,
    workLevelPageSelect,
    workModulePageSelect,
    workModuleTypePageSelect,
    workModuleWayPageSelect,
    getOrderCopySave,
  } from '@/api/order'
  import { getNetworkPageSelect } from '@/api/network'
  import { empPageSelecct } from '@/api/organize'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import {
    orderAnnexUpload,
    orderVideoUpload,
    getUserOrderListWithoutPagination,
  } from '@/api/upload'
  import Commoditynformation from './components/commoditynformation.vue'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import * as _ from 'lodash'
  import useFactorySelectPageService from './services/factorySelectPage'
  import useUserPageSelectService from './services/userPageSelect'
  import { OrderType } from './types'
  import useAddrParseService from '@/views/order/new/services/useAddrParseService'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.order.orderCreate,
  })

  /**
   * 地址识别按钮点击事件
   */
  const onAddrParse = async () => {
    if (!allUserInfo.value.trim()) return
    await addrParse(allUserInfo.value.trim())
    addrs.value = {
      province: addrParseResult.value.province,
      city: addrParseResult.value.city,
      area: addrParseResult.value.area,
      town: '',
      SelectType: false,
    }
    basicData.userId = ''
    basicData.name = addrParseResult.value.username

    // 提取所有数字
    const numbers = allUserInfo.value.match(/\d+/g) || []

    // 第一个11位数字为手机号
    const phone = numbers.find((n) => n.length === 11)
    basicData.phone = phone || ''

    // 第二个11位数字为分机号
    const extension = numbers.find((n, i) => i > 0 && n.length === 11)
    basicData.extensionNbr = extension || ''

    // 处理地址信息
    let str = addrParseResult.value.text
      .replace(addrParseResult.value.username, '')
      .replace(phone || '', '')
      .replace(extension || '', '')
      .trim()

    // 处理详细地址
    basicData.address = str
      .replace(
        /[`:_.~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*（）—— \+ ={}|《》？：“”【】、；‘’，。、]/g,
        '',
      )
      .trim()
  }
  // 使用地址识别服务
  const { addrParseLoading, addrParseResult, addrParse } = useAddrParseService

  // 全局路由对象
  const router = useRouter()
  const route = useRoute()

  // 使用品牌商家下拉数据服务
  const { factoryOptional, getFactorySelectPageLoading, getFactorySelectPageFn } =
    useFactorySelectPageService

  // 使用用户下拉数据服务
  const { get: getUserPageSelect, userPageOptional } = useUserPageSelectService

  const SettingStore = useSettingStore()

  /**
   * 刷新页面
   */
  const refresh = () => {
    SettingStore.setReload()
  }

  // 工单信息表单组件实例
  const orderFormRef = ref<FormInstance>()
  const ruleFormRef2 = ref<FormInstance>()
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null) //地址dom

  // 客户信息div
  const cutomerInfoRef = ref<HTMLDivElement | null>(null)

  const CascaderProps = ref({
    value: 'id',
    label: 'name',
    children: 'selectVos',
    disabled: 'select',
    checkStrictly: true,
  })
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false) //提交工单loading
  const showType = ref(false)
  const grades = ref(null) // 服务级别
  const grade = ref(null) // 服务级别
  const method = ref() // 处理方式
  const userPersons = ref([])
  const network = ref() // 受理网点
  const now = ref(null) // 下单时间
  const fileList = ref([])
  const type = ref(null) // 工单模块分类
  const sources = ref([
    { title: '平台系统报单', value: 1 },
    { title: '扫码报单', value: 2 },
    { title: '小程序报单', value: 3 },
    { title: 'APP报单', value: 4 },
    { title: '平台代商家报单', value: 7 },
    { title: '乐开伙伴云', value: 9 },
  ])

  // 工单模块下拉选项
  const modules = ref<Array<OrderType>>([])

  const loading = ref(false)
  const types = ref(null) //工单模块分类
  const dialogContract = ref(false) //文件查看弹窗
  const file = ref() //文件
  const methodss = ref(null) // 处理方式
  const orderGoodsTypes = ref([]) //添加商品信息
  const networks = ref(null)
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const submitFormShow = ref(false) //用来判断是否有自定义字段
  const customers = ref() // 受理客服列表
  const customer = ref() // 受理客服
  const basicData = reactive({
    source: 7, // 1-平台代建，3-小程序报单，4-APP报单
    moduleId: null, // 工单类型
    overinsured: false, // 质保状态
    content: '', // 故障描述
    userId: '', // 客户ID
    accountNo: '', // 客户账号
    name: '', // 姓名
    phone: '', // 客户手机号
    otherPhone: '', // 其他联系方式
    address: '', // 详细地址
    factoryId: '', // 品牌商家ID
    extensionNbr: '', // 分机号
    isReturn: false, // 是否退回
    customfieldList: [
      {
        contents: [{ id: null, val: null }],
        moduleFieldId: null,
        name: null,
        required: true,
        status: null,
        tip: '',
        type: null,
        uploadQty: null,
        uploadSize: null,
        val: null,
        imgArr: [],
        workFieldId: '',
      },
    ],
  })
  const createUserDialogVisit = ref(false) // 创建客户弹窗
  const createUserRef = ref()
  // 创建客户对象
  const createUserForm = reactive({
    name: '', // 客户姓名
    phone: '', // 客户手机号
  })

  // 校验规则
  const rules = reactive({
    moduleId: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
    source: [{ required: true, message: '请选择工单来源', trigger: 'blur' }],
    overinsured: [{ required: true, message: '请选择质保状态', trigger: ['change', 'blur'] }],
    phone: [
      { required: true, message: '请输入客户手机号', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(basicData.phone)) {
            return callback(new Error('手机号格式错误'))
          }
          callback()
        },
        trigger: ['change'],
      },
    ],
    name: [{ required: true, message: '请输入客户姓名', trigger: ['change', 'blur'] }],
    address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    factoryId: [{ required: true, message: '请选择商家', trigger: 'blur' }],
  })

  // 校验规则
  const createUserFormRules = reactive<FormRules>({
    name: [
      { required: true, message: '客户姓名不能为空', trigger: ['change', 'blur'] },
      { required: true, max: 100, message: '客户姓名长度限制 2~100', trigger: ['change', 'blur'] },
    ],
    phone: [
      { required: true, message: '客户手机号不能为空', trigger: ['change', 'blur'] },
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(createUserForm.phone)) {
            return callback(new Error('手机号格式错误'))
          }
          callback()
        },
        trigger: ['change'],
      },
    ],
  })

  // 取消工单
  const onCancelOrder = () => {
    useTagsViewStore().delView(router.currentRoute.value.path)
    router.push({ path: '/order/list' })
  }

  // 提示重复工单弹窗
  const RepeatRemind = () => {}

  // 提交工单
  const submitOrder = async (formEl: FormInstance | undefined) => {
    console.log(basicData.userId, 'basicData.userId111111')
    const DuplicateWorkOrder = await getUserOrderListWithoutPagination(basicData.userId)
    console.log(DuplicateWorkOrder.data.data.isValidOrder, 'cccccccccccccccccc')

    if (DuplicateWorkOrder.data.data.isValidOrder) {
      try {
        await ElMessageBox.confirm('存在重复工单，是否继续报单?', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
        })
        // ElMessage({
        //   type: 'success',
        //   message: 'Delete completed',
        // })
        console.log('22')
      } catch (error) {
        // 用户点击了"取消"
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
        return
      }
    }
    if (!formEl) return
    await submit2(ruleFormRef2.value)
    let tt = await submitForm(formRef.value)
    if (!formRef.value) {
      tt = true
    }
    await formEl.validate(async (valid) => {
      if (valid && userTrue.value && tt && singleAddressRef.value) {
        const useAddr = singleAddressRef.value.getSelectAddr()
        if (!useAddr.province) {
          ElMessage({
            message: '请选择联系地址',
            type: 'warning',
          })
          return
        }
        if (orderGoodsTypes.value.length == 0) {
          ElMessage({
            message: '至少添加一个商品',
            type: 'warning',
          })
          return
        }

        let data = {
          content: basicData.content, //故障描述
          createTime: now.value, //下单时间
          delImageIds: [], //删除的工单附件ID集合
          delOrderGoodsIds: [], //删除的工单商品对象ID集合
          empId: customer.value, //人员表ID，即客服ID
          id: null, //工单ID，新增不必传，修改必传
          imageVos: [],
          moduleId: basicData.moduleId, //工单模块ID
          networkId: network.value, //网点表ID
          orderGoodsTypes: orderGoodsTypes.value,
          factoryId: basicData.factoryId || '0', // 品牌商家ID
          orderUser: {
            name: basicData.name, //客户姓名
            phone: basicData.phone, //客户手机号
            userId: basicData.userId, //客户ID
            province: useAddr.province, //地址-省
            city: useAddr.city, //地址-市
            area: useAddr.area, //地址-县/区
            town: useAddr.town, //地址-镇
            address: basicData.address, //客户详细地址
            otherPhone: basicData.extensionNbr, //其他联系方式
          },
          overinsured: basicData.overinsured, //质保状态，是否保外：false-保内，true-保外
          source: basicData.source, //工单来源
          threeTypeId: null, //工单模块分类ID3
          threeWayId: null, //工单模块方式ID3
          twoTypeId: null, //工单模块分类ID2
          twoWayId: null, //工单模块方式ID2
          oneTypeId: null, //工单模块分类ID1
          oneWayId: null, //工单模块方式ID1
          workLevelId: grade.value, //工单级别ID
          workFieldVal: [], //工单自定义字段值对象,
          extensionNbr: basicData.extensionNbr,
          isReturn: basicData.isReturn ? 1 : 0,
        }
        // 工单模块分类
        if (type.value?.length > 0) {
          type.value.map((o, i) => {
            if (i == 0) {
              data.oneTypeId = o
            }
            if (i == 1) {
              data.twoWayId = o
            }
            if (i == 2) {
              data.threeTypeId = o
            }
          })
        }
        // 工单模块方式
        if (method.value?.length > 0) {
          method.value.map((o, i) => {
            if (i == 0) {
              data.oneWayId = o
            }
            if (i == 1) {
              data.twoWayId = o
            }
            if (i == 2) {
              data.threeWayId = o
            }
          })
        }
        submitLoading.value = true
        // 判断是否有图片
        if (fileList.value?.length > 0) {
          let imageList = fileList.value.map((o) => {
            return o.file
          })
          // 上传图片
          data.imageVos = []
          const orderAnnexUploadRes = await orderAnnexUpload(imageList)
          if (orderAnnexUploadRes.data.success) {
            for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
              data.imageVos.push({ id: null, image: orderAnnexUploadRes.data.data.rows[i] })
            }
          } else {
            ElMessage({
              message: orderAnnexUploadRes.data.message,
              type: 'error',
            })
          }
        }
        // 判断是否有自定义字段文件上传
        if (submitFormShow.value) {
          const __customFieldList = _.cloneDeep(basicData.customfieldList)
          for (const key in __customFieldList) {
            let item = __customFieldList[key]
            if (item.type == 5 || item.type == 6 || item.type == 7) {
              let img = []
              for (const i in item.imgArr) {
                const it = item.imgArr[i]
                img.push(it.file)
              }
              if (img.length > 0) {
                if (item.type == 7) {
                  const orderVideoUploadRes = await orderVideoUpload(img)
                  if (orderVideoUploadRes.data.success) {
                    item.val = []
                    for (let i = 0; i < orderVideoUploadRes.data.data.rows.length; i++) {
                      item.val.push(orderVideoUploadRes.data.data.rows[i])
                    }
                  } else {
                    ElMessage({
                      message: orderVideoUploadRes.data.message,
                      type: 'error',
                    })
                  }
                } else {
                  const orderAnnexUploadRes = await orderAnnexUpload(img)
                  if (orderAnnexUploadRes.data.success) {
                    item.val = []
                    for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
                      item.val.push(orderAnnexUploadRes.data.data.rows[i])
                    }
                  } else {
                    ElMessage({
                      message: orderAnnexUploadRes.data.message,
                      type: 'error',
                    })
                  }
                }
              }
            }
            if (item.type == 8) {
              if (item.val) {
                item.val = item.val * 2
              }
            }
          }
          data.workFieldVal = _.cloneDeep(__customFieldList)
        }
        data.workFieldVal = data.workFieldVal.map((o) => {
          let tmp = []
          if (Array.isArray(o.val)) {
            tmp = o.val.map((i) => {
              return { id: null, optValue: i }
            })
          } else {
            tmp = [{ id: null, optValue: o.val ? o.val : '' }]
          }

          return { ...o, optionVos: tmp }
        })

        await addSave(data).then((res) => {
          if (res.data.isError)
            ElMessage({
              message: res.data.message,
              type: res.data.success ? 'success' : 'error',
              duration: 2000,
            })
          if (res.data.success) {
            refresh()
            useTagsViewStore().delView(router.currentRoute.value.path)
            router.push({ path: '/order/list' })
          }
        })
        submitLoading.value = false
      } else {
        ElMessage({
          message: '请输入完整信息！',
          type: 'error',
        })
      }
    })
  }
  // 用户信息
  const userTrue = ref(false)
  const submit2 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        userTrue.value = true
      }
    })
  }
  // 自定义字段
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    let tem = true
    await formRef.value.validate((valid) => {
      if (valid) {
        tem = true
      } else {
        tem = false
      }
    })
    return tem
  }
  // 获取图片
  let pass = ref(true)
  const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    if (fileList.value.length >= 10) {
      if (pass.value) {
        ElMessage({
          showClose: true,
          message: `数量不能超过10!`,
          type: 'error',
          duration: 3000,
        })
        pass.value = false
      }

      return
    }
    pass.value = true
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      img: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
      upDatatime: new Date(Date.now()).toISOString().split('T')[0],
    }
    fileList.value.push(tmp)
  }
  // 删除图片
  const deleteItem = (index) => {
    fileList.value = fileList.value.filter((o, i) => i != index)
  }
  // 查看图片
  const lookFile = (val) => {
    file.value = val
    dialogContract.value = true
  }
  //监听弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value = 'about:blank'
    }
  })
  // 添加图片
  const handleChange2 = (uploadFile: UploadFile, item) => {
    if (item.uploadSize < uploadFile.size / 1024 / 1024) {
      onExceedSize(item)
      return
    }
    if (item.imgArr.length >= item.uploadQty) {
      onExceedNub(item)
      return
    }
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
    }
    item.imgArr.push(tmp)
  }
  const onExceedSize = _.debounce((item) => {
    ElMessage({
      showClose: true,
      message:
        item.type == 5
          ? '图片'
          : item.type == 6
          ? '附件'
          : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
      type: 'error',
      duration: 4000,
      offset: 200,
    })
  }, 10)
  const onExceedNub = _.debounce((item) => {
    ElMessage({
      showClose: true,
      message: `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${
        item.uploadQty
      }!`,
      type: 'error',
      duration: 4000,
      offset: 200,
    })
  }, 10)
  // 删除图片
  const deleteItem2 = (bigindex: number, index) => {
    basicData.customfieldList = basicData.customfieldList.map((arr, j) => {
      if ((arr.type == 5 || arr.type == 6 || arr.type == 7) && j == bigindex) {
        arr.imgArr = arr.imgArr.filter((o, i) => i != index)
      }
      return arr
    })
  }

  // header长度
  const headerWidth = ref(0)
  const setH = ref(null)

  const resizeObserver = new ResizeObserver((entries: Array<ResizeObserverEntry>) => {
    headerWidth.value = entries[0].borderBoxSize[0].inlineSize
  })

  // 销毁
  onBeforeUnmount(() => {
    resizeObserver.disconnect()
  })
  //工单分类下拉数据
  const getworkModuleTypePageSelect = async (val, id) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleTypePageSelect(data, id)
    types.value = res.data.data.rows
  }

  //工单分类下拉远程搜索
  const inputChangeType = async (val) => {
    if (basicData.moduleId) {
      await getworkModuleTypePageSelect(val, basicData.moduleId)
    }
  }

  // 处理方式下拉远程搜索
  const inputChangeMethod = async (val) => {
    if (val && basicData.moduleId) {
      await getworkModuleWayPageSelect(val, basicData.moduleId)
    }
  }

  // 获取工单类型下拉选项请求参数
  const getOrderTypeOptionsParam = ref({
    limit: 0,
    page: 0,
    name: '',
  })

  /**
   * 获取工单类型下拉选项
   */
  const handleGetOrderTypeOptions = _.throttle((query: string) => {
    if (query === getOrderTypeOptionsParam.value.name) {
      return false
    }
    getOrderTypeOptionsParam.value.name = query
    getOrderTypeOptionsFn()
  }, 500)

  /**
   * 获取工单类型下拉选项方法
   */
  const getOrderTypeOptionsFn = async () => {
    loading.value = true
    const res = await workModulePageSelect({
      ...getOrderTypeOptionsParam.value,
      factoryId: basicData.factoryId,
    })
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    loading.value = false
  }

  // 获取自定义字段
  const getModuleFieldlist = async (id) => {
    const res = await getModuleField(id)
    res.data.data.row.length > 0 ? (submitFormShow.value = true) : (submitFormShow.value = false)
    basicData.customfieldList = res.data.data.row.map((o) => {
      return {
        ...o,
        val: o.type == 4 || o.type == 5 || o.type == 6 || o.type == 7 ? [] : null,
        imgArr: [],
      }
    })
  }

  /**
   * 切换工单类型
   * @param {Object} val - 工单模块
   */
  const handleChangeModule = (val: OrderType) => {
    type.value = val.type
    // basicData.overinsured = val.overinsured
    if (val.autoDispatchClient) {
      customer.value = 0
    }
    if (val.autoDispatchNetwork) {
      network.value = 0
    }
    getworkModuleWayPageSelect('', val.id)
    getworkModuleTypePageSelect('', val.id)
    getModuleFieldlist(val.id)
    nextTick(() => {
      formRef.value?.resetFields()
    })
  }

  /**
   * 获取服务级别下拉选项
   */
  const getworkLevelPageSelect = _.throttle((val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    workLevelPageSelect(data).then((res) => {
      if (res.data.success) {
        grades.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  /**
   * 工单客服组下拉列表查询
   */
  const getworkTeamPageSelect = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        customers.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  /**
   * 获取服务商下拉选项
   */
  const getNetworkPageSelectList = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    getNetworkPageSelect(data).then((res) => {
      if (res.data.success) {
        networks.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  // 清除客户账号
  const onClearUser = () => {
    basicData.name = ''
    basicData.userId = ''
    basicData.accountNo = ''
    basicData.address = ''
    singleAddressRef.value.clearSelectAddr()
  }
  // 保存新客户
  const onSaveCreateUser = (formEl: FormInstance) => {
    formEl.validate((valid) => {
      if (!valid) {
        return
      }
      onClearUser()
      basicData.userId = '0'
      basicData.accountNo = createUserForm.phone
      basicData.name = createUserForm.name
      basicData.phone = createUserForm.phone
      createUserDialogVisit.value = false
    })
  }
  // ***************客户列表搜索************
  const popoverInputRef = ref()
  const visibleSearch = ref(false)
  // 输入搜索
  const inputSearchName = _.debounce((val) => {
    if (val.trim()) {
      basicData.userId = null
      if (basicData.source == 7) {
        getFacUserList(val.trim())
      } else {
        getselecUser(val.trim())
      }
    }
  }, 600)
  // 获取用户列表
  const getselecUser = (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    userPersons.value = []
    userPageOptional.value = []
    getUserSelect(data).then((res) => {
      if (res.data.success) {
        if (res.data.data.rows.length > 0) {
          userPersons.value = res.data.data.rows
        }
      }
      visibleSearch.value = true
    })
  }
  const getFacUserList = async (val) => {
    userPageOptional.value = []
    userPersons.value = []

    await getUserPageSelect(basicData.factoryId, val)
    visibleSearch.value = true
    // userPageOptional.value.length > 0 ? visibleSearch.value = true : visibleSearch.value = false
  }
  // 用户下拉选项选择改变
  const changeuserPeerson = (item) => {
    visibleSearch.value = false
    nextTick(() => {
      addrs.value = {
        province: item.province,
        city: item.city,
        area: item.area,
        town: item.town,
      }
    })
    basicData.userId = item.id
    basicData.name = item.name
    basicData.phone = item.phone
    basicData.address = item.address
  }

  //  通过模块id 获取处理方式
  const getworkModuleWayPageSelect = async (val, id) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleWayPageSelect(data, id)
    methodss.value = res.data.data.rows
  }
  // 工单分类下拉框出现/隐藏时触发
  const changeType = async () => {
    showType.value = !showType.value
    if (!showType.value) {
      if (!(type.value instanceof Array)) {
        await getworkModuleTypePageSelect('', basicData.moduleId)
      }
    }
  }
  // 处里方式下拉框出现/隐藏时触发
  const changeMmethod = async () => {
    showType.value = !showType.value
    if (!showType.value) {
      if (!(method.value instanceof Array)) {
        await getworkModuleWayPageSelect('', basicData.moduleId)
      }
    }
  }

  const commodityRef = ref(null)
  // 获取复制工单信息
  const getCopyInfo = async (id: string) => {
    getOrderCopySave({ id }).then(async (res) => {
      if (res.data.success) {
        const data = res.data.data.row
        basicData.content = data.content
        now.value = data.createTime
        customer.value = data.empId
        basicData.moduleId = data.moduleId
        network.value = data.networkId
        basicData.factoryId = data.factoryId
        basicData.name = data.orderUser.name
        basicData.phone = data.orderUser.phone
        basicData.userId = data.orderUser.userId
        basicData.address = data.orderUser.address
        basicData.overinsured = data.overinsured
        basicData.source = data.source
        grade.value = data.workLevelId
        basicData.extensionNbr = data.extensionNbr
        basicData.isReturn = data.isReturn === 1

        setTimeout(() => {
          orderGoodsTypes.value = data.orderGoodsTypes
          setTimeout(() => {
            commodityRef.value.setTable()
          })
        })

        // orderGoodsTypes.value.forEach(item => {
        //   commodityRef.value.onCommit(item.type)
        // })

        type.value = []
        if (data.oneTypeId) {
          type.value.push(data.oneTypeId)
        }
        if (data.twoWayId) {
          type.value.push(data.twoWayId)
        }
        if (data.threeTypeId) {
          type.value.push(data.threeTypeId)
        }
        method.value = []
        if (data.oneWayId) {
          method.value.push(data.oneWayId)
        }
        if (data.twoWayId) {
          method.value.push(data.twoWayId)
        }
        if (data.threeWayId) {
          method.value.push(data.threeWayId)
        }
        fileList.value = (data.imageVos || []).map((item) => ({ id: null, url: item.url }))

        await addrParse(data.orderUser.province + data.orderUser.city + data.orderUser.area)
        addrs.value = {
          province: addrParseResult.value.province,
          city: addrParseResult.value.city,
          area: addrParseResult.value.area,
          town: '',
        }
      }
    })
  }

  // 用户的整段信息，包含姓名、手机号、地址
  const allUserInfo = ref('')

  // 监听处里方式下拉选择
  watch(
    () => method.value,
    (n) => {
      if (!n) {
        getworkModuleWayPageSelect('', basicData.moduleId)
      }
    },
  )

  // 监听工单分类下拉选择
  watch(
    () => type.value,
    (n) => {
      if (!n) {
        getworkModuleTypePageSelect('', basicData.moduleId)
      }
    },
  )
  onMounted(() => {
    if (cutomerInfoRef.value) {
      // 监听客户信息div的变化
      resizeObserver.observe(cutomerInfoRef.value)
    }
  })
  const valueSele = ref('')
  const changeValue = () => {
    getFactorySelectPageFn({ limit: 0, name: valueSele.value, page: 0 })
  }
  // 请求获取下拉数据
  onMounted(() => {
    getOrderTypeOptionsFn()
    getFactorySelectPageFn({ limit: 0, name: '', page: 0 })
    handleGetOrderTypeOptions('')
    let data = {
      limit: 0,
      name: '',
      page: 0,
    }
    loading.value = true
    workLevelPageSelect(data).then(async (res) => {
      if (res.data.success) {
        grades.value = await res.data.data.rows
        if (grades.value) {
          grades.value.filter((o) => {
            if (o.select) {
              grade.value = o.id
            }
          })
        }
      }
      loading.value = false
    })
    getworkTeamPageSelect('')
    getNetworkPageSelectList('')
    // 设置当前时间
    now.value =
      new Date(Date.now()).toISOString().split('T')[0] +
      ' ' +
      new Date(Date.now()).toTimeString().split(' ')[0]

    if (route.query.isCopy) {
      getCopyInfo(route.query.id)
    }
  })
  const changeSou = (val) => {}
  const changeFactory = () => {
    valueSele.value = ''
    basicData.moduleId = ''
    changeValue()
    getOrderTypeOptionsFn()
  }
</script>

<style lang="scss" scoped>
  @import './index';

  .userinfo_select_empty {
    display: flex;
    justify-content: center;
  }

  .create-user-btn {
    width: -webkit-fill-available !important;
  }
</style>
<style lang="scss">
  .el-popover.monitor-yt-popover {
    padding: 6px 0;

    .user_item {
      font-size: 12px;
      margin: 0 12px;
      padding: 8px;
      cursor: pointer;
      display: flex;
      align-items: center;
      flex-wrap: nowrap;

      &:hover {
        background-color: rgb(245, 247, 250);
      }
    }
  }
</style>
